<template>
  <div>
    <div class="operation-group">
      <dialogMultiSelectTable
        btnText="框架协议类采购计划选择"
        dialogTitle="选择采购计划"
        errorMessage="请先选择框架协议"
        :isShow="getAgreementSelectStatus"
        :searchInputArr="baseJsObj.planSearchInputArr"
        :tableHeadOptions="baseJsObj.planTableHeadOptions"
        :getTableList="listPurplanPage"
        :optionalParams="planOptionalParams"
        :selectTableList="planSelectTableList"
        @confirm="planConfirm"
      />
      <dialogMultiSelectTable
        btnText="采购方案选择"
        dialogTitle="选择采购方案"
        errorMessage="请先选择供应商 1"
        :isShow="true"
        :searchInputArr="baseJsObj.programmeSearchInputArr"
        :tableHeadOptions="baseJsObj.programmeTableHeadOptions"
        :getTableList="listPursckinfoPage"
        :optionalParams="programmeOptionalParams"
        :selectTableList="programmeSelectTableList"
        @confirm="programmeConfirm"
      />
      <el-button
        class="ml10"
        plain
        type="single-number"
        @click="handleChooseMaterials"
        >物料目录</el-button
      >
      <!-- 批量设置 -->
      <listSettingsBtn
        :dropdownItemArr="baseJsObj.dropdownArr"
        @handleCommand="handleCommand"
      />
      <el-button class="ml10" plain type="single-number" @click="handleCopy"
        >复制行</el-button
      >
      <el-button class="ml10" plain type="single-number" @click="handleRemove"
        >删除行</el-button
      >
    </div>
    <div class="ccui-multifunctional-table-wrapper">
      <ux-grid
        ref="purchaseList"
        widthResize
        keep-source
        show-overflow="title"
        :cell-style="cellStyle"
        :header-cell-class-name="must"
        :max-height="417"
        :edit-config="{ trigger: 'click', mode: 'cell' }"
        @select="listSelectTable"
        @select-all="listSelectTable"
        @row-click="handleRowClick"
      >
        <ux-table-column
          type="checkbox"
          min-width="50"
          align="center"
          fixed="left"
        />

        <ux-table-column
          title="序号"
          type="index"
          align="center"
          min-width="55"
          fixed="left"
        />

        <ux-table-column
          show-overflow-tooltip
          field="materialsCode"
          title="设备物资编码"
          min-width="120"
          fixed="left"
          resizable
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="materialsName"
          title="设备物资名称"
          min-width="300"
          fixed="left"
        />

        <ux-table-column
          show-overflow-tooltip
          field="matDescribe"
          title="设备物资说明"
          min-width="150"
          resizable
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <el-input maxlength="50" v-model="row.matDescribe" />
          </template>
          <template v-slot="{ row }">
            <span class="my-input-sc">{{ row.matDescribe }} </span>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="thirdCategoriesOfName"
          title="分类名称"
          min-width="130"
          resizable
        />

        <ux-table-column
          show-overflow="none"
          field="currentMeasuringUnit"
          title="计量单位"
          min-width="90"
          resizable
        >
          <template v-slot="{ row }">
            <el-tooltip
              v-if="row.isConversion"
              effect="dark"
              :content="thirdCategoriesTooltip(row)"
              placement="top"
            >
              <span>{{ row.currentMeasuringUnit }}</span>
            </el-tooltip>

            <span v-else>{{ row.currentMeasuringUnit }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          field="currentNum"
          title="数量"
          min-width="140"
          resizable
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <el-input
              v-if="isCurrentNumShow(row)"
              v-model="row.currentNum"
              @blur="testColumn($event, row, 'blur', 'currentNum')"
              @focus="testColumn($event, row, 'focus', 'currentNum')"
            />
            <span v-else>{{ row.currentNum }}</span>
          </template>
          <template v-slot="{ row }">
            <span
              :class="{
                'my-input-sc': isCurrentNumShow(row)
              }"
              >{{ row.currentNum }}
            </span>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="currentUnitPriceExcludeTax"
          title="不含税单价"
          min-width="130"
        >
          <template v-slot="{ row }">
            <span>{{ row.currentUnitPriceExcludeTax }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="currentChangeAmtExcludeTax"
          title="不含税金额"
          min-width="140"
        >
          <template v-slot="{ row }">
            <span>{{
              row.currentChangeAmtExcludeTax
                ? Number(row.currentChangeAmtExcludeTax).toFixed(2)
                : ""
            }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          v-if="getMultiRateCode"
          title="税率"
          min-width="100"
          resizable
        >
          <template v-slot="{ row, $rowIndex }">
            <el-select
              v-model="row.taxRatePercent"
              placeholder="请选择"
              @change="handleChange(row, $rowIndex, 'taxRatePercent')"
            >
              <el-option
                v-for="item in Enum.taxRatePercentList"
                :key="item.dicKey"
                :label="item.dicValue"
                :value="item.dicValue"
              >
              </el-option>
            </el-select>
          </template>
        </ux-table-column>

        <ux-table-column
          field="currentUnitPriceIncludeTax"
          title="含税单价"
          min-width="140"
          resizable
          show-overflow="none"
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <!-- 协议显示 tooltip -->
            <div v-if="row.matResource === '0' && row.priceType !== 4">
              <el-tooltip
                effect="dark"
                :content="priceTypeTooltip(row)"
                placement="top"
              >
                <el-input
                  v-if="isCurrentNumShow(row) && row.priceType !== 0"
                  v-model="row.currentUnitPriceIncludeTax"
                  @blur="handleBlur($event, row, 'currentUnitPriceIncludeTax')"
                  @focus="
                    testColumn(
                      $event,
                      row,
                      'focus',
                      'currentUnitPriceIncludeTax'
                    )
                  "
                />
                <span v-else>{{ row.currentUnitPriceIncludeTax }}</span>
              </el-tooltip>
            </div>

            <div v-else>
              <el-input
                v-if="isCurrentNumShow(row) && row.priceType !== 0"
                v-model="row.currentUnitPriceIncludeTax"
                @blur="handleBlur($event, row, 'currentUnitPriceIncludeTax')"
                @focus="
                  testColumn($event, row, 'focus', 'currentUnitPriceIncludeTax')
                "
              />
              <span v-else>{{ row.currentUnitPriceIncludeTax }}</span>
            </div>
          </template>

          <template v-slot="{ row }">
            <el-tooltip
              v-if="row.matResource === '0' && row.priceType !== 4"
              effect="dark"
              :content="priceTypeTooltip(row)"
              placement="top"
            >
              <span
                :class="{
                  'my-input-sc': isCurrentNumShow(row) && row.priceType !== 0
                }"
                >{{ row.currentUnitPriceIncludeTax }}</span
              >
            </el-tooltip>

            <span
              v-else
              :class="{
                'my-input-sc': isCurrentNumShow(row) && row.priceType !== 0
              }"
              >{{ row.currentUnitPriceIncludeTax }}</span
            >
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="currentChangeAmtIncludeTax"
          title="含税金额"
          min-width="140"
          resizable
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <input
              v-if="isCurrentTaxShow(row)"
              type="text"
              class="el-input__inner"
              v-model.lazy="row.currentChangeAmtIncludeTax"
              @blur="
                testColumn($event, row, 'blur', 'currentChangeAmtIncludeTax')
              "
            />
            <span v-else>{{ row.currentChangeAmtIncludeTax }}</span>
          </template>
          <template v-slot="{ row }">
            <span :class="{ 'my-input-sc': isCurrentTaxShow(row) }"
              >{{ row.currentChangeAmtIncludeTax }}
            </span>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="rate"
          title="税额"
          min-width="130"
          resizable
        >
          <template v-slot="{ row }">
            <span>{{ row.rate }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="address"
          title="交货地点"
          min-width="200"
          resizable
        >
          <template v-slot="{ row }">
            <div class="ellipsis">
              {{ row.address || (isCurrentNumShow(row) ? "请选择" : "") }}
            </div>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="deliveryTime"
          title="交货时间"
          min-width="170"
        >
          <template v-slot="{ row }">
            <el-date-picker
              v-if="isCurrentNumShow(row)"
              v-model="row.deliveryTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            />
            <span v-else>{{ row.deliveryTime }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="manufacturer"
          title="生产厂家/品牌"
          min-width="200"
          resizable
        >
          <template v-slot="{ row }">
            <el-input
              v-if="isCurrentNumShow(row)"
              class="input-readonly"
              show-overflow-tooltip
              :readonly="row.manufacturerDisabled"
              v-model="row.manufacturer"
              placeholder="请输入生产厂家/品牌"
              maxlength="200"
            >
              <el-button slot="append" @click="manufacturerClick(row)"
                >选择</el-button
              >
            </el-input>
            <span v-else>{{ row.manufacturer }}</span>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="purchasePlanCode"
          title="采购计划编号"
          min-width="130"
          resizable
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="purchasePlanName"
          title="采购计划名称"
          min-width="130"
          resizable
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="planCode"
          title="方案编号"
          min-width="130"
          resizable
        />

        <ux-table-column
          show-overflow-tooltip
          field="planName"
          title="方案名称"
          min-width="130"
          resizable
        />

        <ux-table-column
          show-overflow-tooltip
          field="protocalCode"
          title="协议编号"
          min-width="130"
          resizable
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="protocalName"
          title="协议名称"
          min-width="130"
          resizable
        >
        </ux-table-column>
      </ux-grid>
    </div>

    <!-- 选择物资 -->
    <chooseMaterials
      ref="materialsFormVisible"
      :functionObject="materialsFunctionObj"
      @confirm="handleSelect"
    />

    <!-- 计量单位 -->
    <el-dialog
      title="选择计量单位"
      class="metering-dialog"
      :visible.sync="dialogVisible"
      :before-close="dialogBeforeClose"
    >
      <el-form ref="form" :model="form" label-width="126px">
        <el-form-item label="单位转换设置：">
          <el-input v-model="form.a" disabled />
          <i class="dialog-icon icon-ccui-switch" />
          <el-select filterable v-model="form.b" placeholder="请选择">
            <el-option
              v-for="item in Enum.currentMeasuringUnitList"
              :key="item.dicKey"
              :label="item.dicValue"
              :value="item.dicValue"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="单位转换比例设置：">
          <el-input v-model="form.c">
            <template slot="append">{{ form.a }}</template>
          </el-input>
          <span class="dialog-span">=</span>
          <el-input v-model="form.d" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfim">确 定</el-button>
      </div>
    </el-dialog>

    <listSettings
      ref="listSettings"
      btnText="批量设置"
      :dialogTitle="listSettingsDialogTitle"
      :isSelect="!!listTableData.length"
      :selectTableList="listTableData"
      :status="listSettingsStatus"
      :detail="listSettingsDetail"
      @ok="handlerChange"
    />

    <!-- 选择厂家 -->
    <chooseStatement
      ref="chooseStatement"
      :setTableList="statementList"
      :selectData.sync="statementSelectData"
      :rowParams="statementRowParams"
      :pages="statementPages"
      @autocompleteSelect="autocompleteSelect"
      @ok="confirmSelect"
    />
  </div>
</template>

<script>
import variedMaterials from "@/app/contractManagement/mixins/variedMaterials";
import { mapGetters } from "vuex";
import { listPurplanPage, listPursckinfoPage } from "../api";
import { formatNumber, setToFixed } from "@/basa/utils";
import {
  qryMatSubCataTree, // 物装树
  qryListMateriaCata, // 物装树
  getListCommonCodePage, // 常用编码
  listCommonCategoryPage // 常用类别
} from "@/basa/api";
import jsObj from "../js";
import baseJsObj from "@/app/contractManagement/materialContract/contractDraft/js";

export default {
  name: "purchaseList",
  mixins: [variedMaterials("change")],
  data() {
    return {
      jsObj,
      baseJsObj,
      materialsFunctionObj: {
        materialTree: qryMatSubCataTree, // 物装树
        materialList: qryListMateriaCata, // 物装列表
        commonCodes: getListCommonCodePage, // 常用编码
        commonCategories: listCommonCategoryPage // 常用类别
      }
    };
  },
  methods: {
    // 表格input校验
    testColumn(e, row, eventType, nameModel) {
      if (eventType === "blur") {
        if (e !== null) {
          e.target.style.border = `1px solid ${
            row[nameModel] ? "#ccc" : "red"
          }`;
        }

        // 截取小数后位数
        if (row[nameModel]) {
          if (
            this.getInputRule(row[nameModel]) &&
            [
              "currentNum",
              "currentUnitPriceIncludeTax",
              "currentChangeAmtIncludeTax"
            ].includes(nameModel)
          ) {
            row[nameModel] = formatNumber(
              Number(row[nameModel]),
              nameModel === "currentNum" ? 3 : 2
            );
          }

          // 计算 start
          if (this.isCurrentNumShow(row)) {
            if (
              row.currentNum &&
              row.currentUnitPriceIncludeTax &&
              this.getInputRule(row.currentNum) &&
              this.getInputRule(row.currentUnitPriceIncludeTax)
            ) {
              const newTaxRate = new this.$BigNumber(this.taxRateParams).plus(
                1
              );
              // 合同金额
              const price = setToFixed(
                new this.$BigNumber(row.currentNum).multipliedBy(
                  row.currentUnitPriceIncludeTax
                ),
                2
              );
              // 计算含税金额(含税)(单行)
              row.currentChangeAmtIncludeTax = setToFixed(price, 2);

              if (!this.getMultiRateCode) {
                const amtExcludeTax = new this.$BigNumber(price).dividedBy(
                  newTaxRate
                );
                // 计算不含税单价
                row.currentUnitPriceExcludeTax = setToFixed(
                  new this.$BigNumber(row.currentUnitPriceIncludeTax).dividedBy(
                    newTaxRate
                  ),
                  2
                );
                // 计算不含税金额
                row.currentChangeAmtExcludeTax = setToFixed(amtExcludeTax, 2);
                // 计算税额
                row.rate = setToFixed(
                  new this.$BigNumber(price).minus(amtExcludeTax),
                  2
                );
              } else {
                if (row.taxRatePercent != "免税" && row.taxRatePercent) {
                  const val = row.taxRatePercent.substring(
                    0,
                    row.taxRatePercent.indexOf("%")
                  );
                  row.taxRate = Number(val) / 100;
                } else {
                  row.taxRate = 0;
                }
                const newTaxRate = new this.$BigNumber(row.taxRate).plus(1);
                const amtExcludeTax = new this.$BigNumber(price).dividedBy(
                  newTaxRate
                );
                // 计算不含税金额
                row.currentChangeAmtExcludeTax = setToFixed(amtExcludeTax, 2);
                // 计算不含税单价
                row.currentUnitPriceExcludeTax = setToFixed(
                  new this.$BigNumber(row.currentUnitPriceIncludeTax).dividedBy(
                    newTaxRate
                  ),
                  2
                );
                // 计算税额
                row.rate = setToFixed(
                  new this.$BigNumber(price).minus(amtExcludeTax),
                  2
                );
              }
            } else this.clearOrdinaryCompute(row);
          }

          // 特殊 code 值的计算
          if (this.isCurrentTaxShow(row)) {
            if (
              row.currentChangeAmtIncludeTax &&
              this.getInputRule(row.currentChangeAmtIncludeTax)
            ) {
              if (!this.getMultiRateCode) {
                // 1 + 税率
                const newTaxRate = new this.$BigNumber(this.taxRateParams).plus(
                  1
                );
                // 不含税金额
                const amountExcludingTax = new this.$BigNumber(
                  row.currentChangeAmtIncludeTax
                ).dividedBy(newTaxRate);
                // 计算不含税金额
                row.currentChangeAmtExcludeTax = setToFixed(
                  amountExcludingTax,
                  2
                );

                // 计算税额
                row.rate = setToFixed(
                  new this.$BigNumber(row.currentChangeAmtIncludeTax).minus(
                    amountExcludingTax
                  ),
                  2
                );
              } else {
                // 截取税率
                if (row.taxRatePercent != "免税" && row.taxRatePercent) {
                  const val = row.taxRatePercent.substring(
                    0,
                    row.taxRatePercent.indexOf("%")
                  );
                  row.taxRate = Number(val) / 100;
                } else {
                  row.taxRate = 0;
                }
                // 1 + 税率
                const newTaxRate = new this.$BigNumber(row.taxRate).plus(1);
                // 不含税金额
                const amountExcludingTax = new this.$BigNumber(
                  row.currentChangeAmtIncludeTax
                ).dividedBy(newTaxRate);
                // 计算不含税金额
                row.currentChangeAmtExcludeTax = setToFixed(
                  amountExcludingTax,
                  2
                );
                // 计算税额
                row.rate = setToFixed(
                  new this.$BigNumber(row.currentChangeAmtIncludeTax).minus(
                    amountExcludingTax
                  ),
                  2
                );
              }
            } else this.clearSpecialCompute(row);
          }

          // 算总和
          const isIncludesTax = this.purchaseList.every(
            _ => _.currentChangeAmtIncludeTax
          );
          const isExcludesTax = this.purchaseList.every(
            _ => _.currentChangeAmtExcludeTax
          );
          // 算出总和传给基础信息
          if (isIncludesTax && isExcludesTax) {
            // 计算合同金额(含税)(基础信息总和)
            const setContractPriceIncludeTax = setToFixed(
              this.purchaseList.reduce(
                (pre, cur) =>
                  new this.$BigNumber(pre).plus(
                    Number(cur.currentChangeAmtIncludeTax)
                  ),
                0
              ),
              2
            );
            // 计算合同金额(不含税)(基础信息总和)
            const setContractPriceExcludeTax = setToFixed(
              this.purchaseList.reduce(
                (pre, cur) =>
                  new this.$BigNumber(pre).plus(
                    Number(cur.currentChangeAmtExcludeTax)
                  ),
                0
              ),
              2
            );
            this.$bus.$emit("setPriceSum", {
              setContractPriceIncludeTax,
              setContractPriceExcludeTax
            });
          }
        } else {
          // 普通计算
          if (this.isCurrentNumShow(row)) this.clearOrdinaryCompute(row);
          // 特殊 code 值的计算
          if (this.isCurrentTaxShow(row)) this.clearSpecialCompute(row);
        }
        // 计算 end
      }

      if (eventType === "focus") {
        if (e !== null) {
          e.target.style.border = "1px solid #0089EF";
        }
      }
    },

    priceTypeTooltip(row) {
      // 0: '执行价'  1: '限高价'  2: '限高限低价'  3: '参考价'  4: '其他'
      let str = `${baseJsObj.priceTypeMap[row.priceType]}：`;

      if ([0, 3].includes(row.priceType)) {
        return `${str + setToFixed(row.currentUnitPriceIncludeTaxStr, 2)}`;
      }

      if (row.priceType === 2) {
        return `${str + setToFixed(row.minPrice, 2)} --- ${setToFixed(
          row.maxPrice,
          2
        )}`;
      }

      if ([1, 2].includes(row.priceType)) {
        return `${str + setToFixed(row.maxPrice, 2)}`;
      }
    },

    listPursckinfoPage,
    listPurplanPage
  },
  watch: {
    getMultiRateCode: {
      immediate: true,
      handler(newVal) {
        // 查找税率对应的索引值
        const index = baseJsObj.dropdownArr.findIndex(
          _ => _.command === "taxRate"
        );
        // 控制批量设置里的税率
        baseJsObj.dropdownArr[index].disabled = !newVal;
      }
    }
  },
  computed: {
    ...mapGetters(["getMultiRateCode"])
  }
};
</script>

<style lang="scss" scoped>
@import "@/app/contractManagement/css/purchaseList.scss";
</style>
